
#include <Poco/Net/TCPServer.h>
#include <Poco/Net/ServerSocket.h>
#include <Poco/Util/ServerApplication.h>
#include <Poco/Util/Option.h>
#include <Poco/Util/OptionSet.h>
#include <Poco/Util/HelpFormatter.h>

#include <iostream>
#include <string>

using Poco::Net::TCPServer;
using Poco::Net::ServerSocket;
using Poco::Util::ServerApplication;
using Poco::Util::Option;
using Poco::Util::OptionSet;
using Poco::Util::OptionCallback;
using Poco::Util::HelpFormatter;

#include "TaskLogin.h"
#include "ConnectionFactory.h"
//#include "LoginTask.login.pb.h"

class LoginServer : public ServerApplication
{
public:
	LoginServer() {
	}
	virtual ~LoginServer() {
	}

protected:
	virtual void initialize(Application& self) {
		loadConfiguration(); // load default configuration files, if present
		ServerApplication::initialize(self);
		logger().information("starting up");
		//GOOGLE_PROTOBUF_VERIFY_VERSION;


	}

	virtual void uninitialize() {
		//google::protobuf::ShutdownProtobufLibrary();
		logger().information("shutting down");
		ServerApplication::uninitialize();
	}

	virtual void defineOptions(OptionSet& options) {
		ServerApplication::defineOptions(options);

		options.addOption(
			Option("help", "h", "display help information on command line arguments")
			.required(false)
			.repeatable(false)
			.callback(OptionCallback<LoginServer>(this, &LoginServer::handleHelp)));
	}

	virtual void handleHelp(const std::string& name, const std::string& value) {
		displayHelp();
		stopOptionsProcessing();
	}

	void displayHelp() {
		HelpFormatter helpFormatter(options());
		helpFormatter.setCommand(commandName());
		helpFormatter.setUsage("OPTIONS");
		helpFormatter.setHeader("A sample server application that demonstrates some of the features of the Util::ServerApplication class.");
		helpFormatter.format(std::cout);
	}

	virtual int main(const std::vector<std::string>& args) {
		// get parameters from configuration file
		unsigned short port = (unsigned short) config().getInt("LoginServer.port", 6699);
		unsigned short bufsize = (unsigned short) config().getInt("LoginServer.buffersize", 1024);
		// 1. Bind a ServerSocket with an address
		ServerSocket svs(port);
		// 2. Pass the ServerSocket to a TCPServer
		TCPServer server(new ConnectionFactory(), svs);
		// 3. Start the TCPServer
		server.start();
		// 4. Wait for termination
		waitForTerminationRequest();
		// 5. Stop the TCPServer
		server.stop();

		return Application::EXIT_OK;
	}

private:
};

POCO_SERVER_MAIN(LoginServer)
